<template>
  <ElDialog
    :model-value="visible"
    :title="title"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      @keyup.enter="handleSubmit"
    >
      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="品牌名称" prop="brandName">
            <ElInput
              v-model="formData.brandName"
              placeholder="请输入品牌名称"
              maxlength="50"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="品牌编码" prop="brandCode">
            <ElInput
              v-model="formData.brandCode"
              placeholder="请输入品牌编码"
              maxlength="30"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="品牌Logo" prop="logo">
            <div class="logo-upload">
              <ElUpload
                class="logo-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="handleLogoSuccess"
                accept="image/*"
              >
                <img
                  v-if="formData.logo"
                  :src="formData.logo"
                  class="logo-preview"
                />
                <ElIcon v-else class="logo-uploader-icon"><Plus /></ElIcon>
              </ElUpload>
              <div class="upload-tips">
                <p>支持 JPG、PNG 格式，大小不超过 2MB</p>
                <p>建议尺寸：100 x 100 像素</p>
              </div>
            </div>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="状态" prop="status">
            <ElRadioGroup v-model="formData.status">
              <ElRadio :value="1">正常</ElRadio>
              <ElRadio :value="0">停用</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="备注" prop="remark">
            <ElInput
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              maxlength="200"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <ElButton @click="handleClose">取消</ElButton>
      <ElButton type="primary" :loading="submitting" @click="handleSubmit">
        确定
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance, FormRules, UploadProps } from "element-plus";

defineOptions({ name: "WmsItemBrandDialog" });

// Props
interface Props {
  visible: boolean;
  type: "add" | "edit";
  brandData?: WMS.Basic.ItemBrandInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  brandData: null,
});

// Emits
const emit = defineEmits<{
  "update:visible": [visible: boolean];
  submit: [data: WMS.Basic.ItemBrandInfo];
}>();

// Form ref
const formRef = ref<FormInstance>();

// 提交状态
const submitting = ref(false);

// 弹窗标题
const title = computed(() => {
  return props.type === "edit" ? "编辑品牌" : "新增品牌";
});

// 表单数据
const formData = reactive<Partial<WMS.Basic.ItemBrandInfo>>({
  brandName: "",
  brandCode: "",
  logo: "",
  status: 1,
  remark: "",
});

// 表单验证规则
const rules: FormRules = {
  brandName: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  brandCode: [
    { required: true, message: "请输入品牌编码", trigger: "blur" },
    { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_-]+$/,
      message: "只能包含字母、数字、下划线和中划线",
      trigger: "blur",
    },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 监听数据变化，初始化表单
watch(
  () => [props.visible, props.brandData],
  () => {
    if (props.visible) {
      resetForm();
      if (props.type === "edit" && props.brandData) {
        Object.assign(formData, {
          id: props.brandData.id,
          brandName: props.brandData.brandName,
          brandCode: props.brandData.brandCode,
          logo: props.brandData.logo || "",
          status: props.brandData.status,
          remark: props.brandData.remark || "",
        });
      }
    }
  },
  { immediate: true },
);

// 重置表单
const resetForm = () => {
  formData.brandName = "";
  formData.brandCode = "";
  formData.logo = "";
  formData.status = 1;
  formData.remark = "";
  formRef.value?.clearValidate();
};

// Logo上传前验证
const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// Logo上传成功
const handleLogoSuccess = (response: any, file: any) => {
  // 这里应该调用实际的上传API，暂时使用本地预览
  const reader = new FileReader();
  reader.onload = (e) => {
    formData.logo = e.target?.result as string;
  };
  reader.readAsDataURL(file.raw);
};

// 关闭弹窗
const handleClose = () => {
  emit("update:visible", false);
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    const submitData = { ...formData } as WMS.Basic.ItemBrandInfo;
    emit("submit", submitData);
  } catch (error) {
    console.error("Form validation failed:", error);
  } finally {
    submitting.value = false;
  }
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 20px 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.logo-upload {
  display: flex;
  gap: 16px;

  .logo-uploader {
    .logo-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: var(--el-color-primary);
        color: var(--el-color-primary);
      }
    }

    .logo-preview {
      width: 100px;
      height: 100px;
      border-radius: 6px;
      object-fit: cover;
      border: 1px solid #ddd;
    }
  }

  .upload-tips {
    flex: 1;

    p {
      margin: 0 0 4px 0;
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}
</style>
